﻿using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Scribd.Net;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["signedin"] == null)
        {
            Scribd.Net.Service.APIKey = "APIKEY";
            Scribd.Net.Service.SecretKey = "SECRETKEY";
            Scribd.Net.Service.PublisherID = "PUBLISHERID";
            Session["signedin"] = Scribd.Net.User.Login("username", "password").ToString();
        }

        if (bool.Parse(Session["signedin"].ToString()) == false)
        {
            Response.Write("Invalid login.");
            Response.End();
        }
        else
        {
            this.username.Text = Scribd.Net.Service.User.Name;

            if (IsPostBack)
            {
                // Search
            }
            else
            {
                Scribd.Net.Service.User.ReloadDocuments();
                BindDocuments(Scribd.Net.Service.User.Documents);
            }
        }

        this.embedLocation.Controls.Clear();

        if (!string.IsNullOrEmpty(Request.QueryString["id"]))
        {
            Document _doc = new Document();
            _doc = Document.Download(int.Parse(Request.QueryString["id"]));
            this.embedLocation.Controls.Add(new HtmlGenericControl("div"));
            ((HtmlGenericControl)this.embedLocation.Controls[0]).InnerHtml = _doc.GetEmbedCode();
        }
        else
        {
            this.embedLocation.Controls.Add(new HtmlGenericControl("span"));
            ((HtmlGenericControl)this.embedLocation.Controls[0]).InnerText = "No document selected.";
        }
    }
    protected void searchButton_Click(object sender, EventArgs e)
    {
        Scribd.Net.Search.Criteria _criteria = new Search.Criteria();
        _criteria.Query = this.searchTerm.Text;
        _criteria.Scope = SearchScope.User;
        _criteria.StartIndex = 0;
        _criteria.MaxResults = 100;
        
        Scribd.Net.Search.Result _result = Scribd.Net.Search.Find(_criteria);

        BindDocuments(_result.Documents);
    }

    private void BindDocuments(System.Collections.Generic.List<Document> documents)
    {
        this.documentListView.DataSource = documents;
        this.documentListView.DataBind();
    }
}
